<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!-- 引入统一样式文件 -->
<link rel="stylesheet" href="../static/css/library-common.css">

<div class="card">
    <!-- 新增按钮：打开新增借阅模态窗 -->
    <button class="btn btn-primary" onclick="openAddModal()">新增借阅</button>

    <!-- 搜索表单：支持多条件搜索 -->
    <div class="search-bar">
        <form action="borrow" method="get">
            <input type="hidden" name="action" value="list">
            <input type="text" name="username" placeholder="输入借阅人名" value="${param.username}"/>
            <input type="text" name="bookTitle" placeholder="输入书籍名" value="${param.bookTitle}"/>
            <select name="status">
                <option value="">选择状态</option>
                <option value="RETURNED" ${param.status == 'RETURNED' ? 'selected' : ''}>已归还</option>
                <option value="UNRETURNED" ${param.status == 'UNRETURNED' ? 'selected' : ''}>未归还</option>
            </select>
            <button type="submit" class="btn btn-primary">搜索</button>
        </form>
    </div>

    <!-- 借阅表格：使用JSTL遍历数据，状态样式区分 -->
    <table>
        <thead>
        <tr>
            <th>序号</th>
            <th>借阅人</th>
            <th>借阅书本</th>
            <th>书本ISBN</th>
            <th>超时罚款（元/天）</th>
            <th>借阅日期</th>
            <th>预计归还</th>
            <th>状态</th>
            <th>是否逾期</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${borrows}" var="borrow" varStatus="status">
            <tr align="center">
                <td>${status.count}</td>
                <td>${borrow.username}</td>
                <td>${borrow.bookTitle}</td>
                <td>${borrow.isbn}</td>
                <td>${borrow.finePerDay}</td>
                <td><fmt:formatDate value="${borrow.borrowDate}" pattern="yyyy/MM/dd"/></td>
                <td><fmt:formatDate value="${borrow.expectReturnDate}" pattern="yyyy/MM/dd"/></td>
                <td>
                    <c:choose>
                        <c:when test="${borrow.status == 'RETURNED'}">
                            <span class="status-success">已归还</span>
                        </c:when>
                        <c:otherwise>
                            <span class="status-warning">未归还</span>
                        </c:otherwise>
                    </c:choose>
                </td>
                <td>
                    <c:choose>
                        <c:when test="${borrow.overdue}">
                            <span class="status-danger">是</span>
                        </c:when>
                        <c:otherwise>
                            <span class="status-success">否</span>
                        </c:otherwise>
                    </c:choose>
                </td>
                <td>
                    <a href="javascript:void(0)"
                       onclick="openEditModal(${borrow.id}, '${borrow.username}', '${borrow.bookTitle}', '${borrow.isbn}', ${borrow.finePerDay}, '${borrow.borrowDate}', '${borrow.expectReturnDate}', '${borrow.status}')"
                       style="color: #1890ff; margin-right: 10px;">编辑</a>
                    <a href="javascript:void(0)"
                       onclick="showDeleteConfirm(${borrow.id})"
                       style="color: #ff4d4f; margin-right: 10px;">删除</a>
                    <!-- 仅未归还状态显示"归还"按钮 -->
                    <c:if test="${borrow.status == 'UNRETURNED'}">
                        <a href="javascript:void(0)"
                           onclick="showReturnConfirm(${borrow.id})"
                           style="color: #52c41a;">归还</a>
                    </c:if>
                </td>
            </tr>
        </c:forEach>
        <!-- 空数据提示 -->
        <c:if test="${empty borrows}">
            <tr>
                <td colspan="10" align="center">暂无借阅记录</td>
            </tr>
        </c:if>
        </tbody>
    </table>
</div>

<!-- 新增借阅模态窗 -->
<div class="modal-overlay" id="addOverlay"></div>
<div class="modal-window" id="addModal">
    <span class="close-btn" onclick="closeAddModal()">&times;</span>
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">新增借阅记录</h3>

    <form action="borrow?action=add" method="post">
        <div class="form-group">
            <label for="addUsername">借阅人：</label>
            <input type="text" id="addUsername" name="username" required placeholder="请输入借阅人用户名"/>
        </div>
        <div class="form-group">
            <label for="addBookTitle">借阅书本：</label>
            <input type="text" id="addBookTitle" name="bookTitle" required placeholder="请输入书籍名称"/>
        </div>
        <div class="form-group">
            <label for="addIsbn">书本ISBN：</label>
            <input type="text" id="addIsbn" name="isbn" required placeholder="请输入书籍ISBN"/>
        </div>
        <div class="form-group">
            <label for="addFinePerDay">超时罚款（元/天）：</label>
            <input type="number" step="0.01" min="0" id="addFinePerDay" name="finePerDay" required value="1"/>
        </div>
        <div class="form-group">
            <label for="addBorrowDate">借阅日期：</label>
            <input type="date" id="addBorrowDate" name="borrowDate" required/>
        </div>
        <div class="form-group">
            <label for="addExpectReturnDate">预计归还日期：</label>
            <input type="date" id="addExpectReturnDate" name="expectReturnDate" required/>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">保存</button>
            <button type="button" class="btn btn-secondary" onclick="closeAddModal()">取消</button>
        </div>
    </form>
</div>

<!-- 编辑借阅模态窗 -->
<div class="modal-overlay" id="editOverlay"></div>
<div class="modal-window" id="editModal">
    <span class="close-btn" onclick="closeEditModal()">&times;</span>
    <h3 style="text-align: center; margin-bottom: 20px; color: #333;">编辑借阅记录</h3>

    <form action="borrow?action=update" method="post">
        <input type="hidden" id="editId" name="id">
        <div class="form-group">
            <label for="editUsername">借阅人：</label>
            <input type="text" id="editUsername" name="username" required/>
        </div>
        <div class="form-group">
            <label for="editBookTitle">借阅书本：</label>
            <input type="text" id="editBookTitle" name="bookTitle" required/>
        </div>
        <div class="form-group">
            <label for="editIsbn">书本ISBN：</label>
            <input type="text" id="editIsbn" name="isbn" required/>
        </div>
        <div class="form-group">
            <label for="editFinePerDay">超时罚款（元/天）：</label>
            <input type="number" step="0.01" min="0" id="editFinePerDay" name="finePerDay" required/>
        </div>
        <div class="form-group">
            <label for="editBorrowDate">借阅日期：</label>
            <input type="date" id="editBorrowDate" name="borrowDate" required/>
        </div>
        <div class="form-group">
            <label for="editExpectReturnDate">预计归还日期：</label>
            <input type="date" id="editExpectReturnDate" name="expectReturnDate" required/>
        </div>
        <div class="form-group">
            <label for="editStatus">状态：</label>
            <select id="editStatus" name="status" required>
                <option value="UNRETURNED">未归还</option>
                <option value="RETURNED">已归还</option>
            </select>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">更新</button>
            <button type="button" class="btn btn-secondary" onclick="closeEditModal()">取消</button>
        </div>
    </form>
</div>

<!-- 删除确认框 -->
<div class="modal-overlay" id="deleteOverlay"></div>
<div class="confirm-dialog" id="deleteConfirm">
    <p>确定要删除该借阅记录吗？此操作不可撤销。</p>
    <input type="hidden" id="deleteId">
    <button class="btn btn-danger" onclick="confirmDelete()">确认删除</button>
    <button class="btn btn-secondary" onclick="cancelDelete()">取消</button>
</div>

<!-- 归还确认框（单独处理归还操作） -->
<div class="modal-overlay" id="returnOverlay"></div>
<div class="confirm-dialog" id="returnConfirm">
    <p>确定要办理归还吗？将自动计算逾期费用。</p>
    <input type="hidden" id="returnId">
    <button class="btn btn-primary" onclick="confirmReturn()">确认归还</button>
    <button class="btn btn-secondary" onclick="cancelReturn()">取消</button>
</div>

<script>
    // 新增借阅模态窗控制
    function openAddModal() {
        document.getElementById("addOverlay").style.display = "block";
        document.getElementById("addModal").style.display = "block";
    }

    function closeAddModal() {
        document.getElementById("addOverlay").style.display = "none";
        document.getElementById("addModal").style.display = "none";
    }

    // 编辑借阅模态窗控制
    function openEditModal(id, username, bookTitle, isbn, finePerDay, borrowDate, expectReturnDate, status) {
        document.getElementById("editId").value = id;
        document.getElementById("editUsername").value = username;
        document.getElementById("editBookTitle").value = bookTitle;
        document.getElementById("editIsbn").value = isbn;
        document.getElementById("editFinePerDay").value = finePerDay;
        document.getElementById("editBorrowDate").value = borrowDate.split(" ")[0];
        document.getElementById("editExpectReturnDate").value = expectReturnDate.split(" ")[0];
        document.getElementById("editStatus").value = status;

        document.getElementById("editOverlay").style.display = "block";
        document.getElementById("editModal").style.display = "block";
    }

    function closeEditModal() {
        document.getElementById("editOverlay").style.display = "none";
        document.getElementById("editModal").style.display = "none";
    }

    // 删除确认控制
    function showDeleteConfirm(id) {
        document.getElementById("deleteId").value = id;
        document.getElementById("deleteOverlay").style.display = "block";
        document.getElementById("deleteConfirm").style.display = "block";
    }

    function confirmDelete() {
        const id = document.getElementById("deleteId").value;
        window.location.href = "borrow?action=delete&id=" + id;
    }

    function cancelDelete() {
        document.getElementById("deleteOverlay").style.display = "none";
        document.getElementById("deleteConfirm").style.display = "none";
    }

    // 归还确认控制（单独逻辑）
    function showReturnConfirm(id) {
        document.getElementById("returnId").value = id;
        document.getElementById("returnOverlay").style.display = "block";
        document.getElementById("returnConfirm").style.display = "block";
    }

    function confirmReturn() {
        const id = document.getElementById("returnId").value;
        window.location.href = "borrow?action=return&id=" + id; // 调用归还接口
    }

    function cancelReturn() {
        document.getElementById("returnOverlay").style.display = "none";
        document.getElementById("returnConfirm").style.display = "none";
    }

    // 通用关闭逻辑：遮罩层点击/ESC键
    document.getElementById("addOverlay").addEventListener("click", closeAddModal);
    document.getElementById("editOverlay").addEventListener("click", closeEditModal);
    document.getElementById("deleteOverlay").addEventListener("click", cancelDelete);
    document.getElementById("returnOverlay").addEventListener("click", cancelReturn);

    document.addEventListener("keydown", function (e) {
        if (e.key === "Escape") {
            closeAddModal();
            closeEditModal();
            cancelDelete();
            cancelReturn();
        }
    });
</script>
